package org.doubango.ngn.h264

import com.evendai.loglibrary.Timber
import java.util.concurrent.LinkedBlockingDeque

class H264ToMp4SaverThread : Thread(TAG) {
    private var mBlockingDeque: LinkedBlockingDeque<H264Data>? = null
    private var mH264ToMp4Saver: H264ToMp4Saver? = null
    private var frameLossCount: Int = 0
    private lateinit var h264Data: H264Data

    init {
        if (needRecordVideo) {
            mBlockingDeque = LinkedBlockingDeque(5)
            mH264ToMp4Saver = H264ToMp4Saver()
        }
    }

    fun addH264Data(h264Data: H264Data) {
        if (needRecordVideo) {
            val offer = mBlockingDeque!!.offer(h264Data)
            if (!offer) {
                Timber.i("保存H264为Mp4文件时丢帧：${++frameLossCount}帧")
            }
        }
    }

    override fun run() {
        try {
            while (!isInterrupted && needRecordVideo) {
                h264Data = mBlockingDeque!!.take()
                mH264ToMp4Saver!!.h264ToMp4(h264Data)
            }
        } catch (e: InterruptedException) {
            Timber.w("别慌，线程是正常中断的，线程名称 = ${currentThread().name}")
        } catch (e: Exception) {
            Timber.e(e,"把H264保存为mp4时出现异常")
            mH264ToMp4Saver!!.checkHasSDCard()
        }
    }

    fun close() {
        if (needRecordVideo) {
            mH264ToMp4Saver!!.saveMp4File()
            interrupt()
        }
    }

    companion object {
        private val TAG = H264ToMp4SaverThread::class.java.simpleName
        /** 控制是否需要录视频，默认为true录视频 */
        var needRecordVideo = false
    }

}
